#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git Hooks 动态配置系统 - 系统测试脚本
用于验证系统各个组件是否正常工作
"""

import sys
import os
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def test_imports():
    """测试模块导入"""
    print("测试模块导入...")
    
    try:
        # 测试核心模块
        from core.config_parser import ConfigParser, GlobalConfig, HookConfig, TaskConfig
        print("✓ 配置解析器导入成功")
        
        from core.task_executor import TaskExecutor, TaskResult, TaskStatus
        print("✓ 任务执行器导入成功")
        
        from core.hook_manager import HookManager, HookType, HookContext
        print("✓ Hook 管理器导入成功")
        
        return True
    except Exception as e:
        print(f"✗ 模块导入失败: {e}")
        return False

def test_dependencies():
    """测试依赖"""
    print("\n测试依赖...")
    
    try:
        import yaml
        print("✓ PyYAML 可用")
    except ImportError:
        print("✗ PyYAML 未安装")
        return False
    
    try:
        from pathlib import Path
        print("✓ pathlib 可用")
    except ImportError:
        print("✗ pathlib 未安装")
        return False
    
    return True

def test_config_parser():
    """测试配置解析器"""
    print("\n测试配置解析器...")
    
    try:
        from core.config_parser import ConfigParser
        
        # 创建配置解析器
        parser = ConfigParser("config")
        
        # 测试加载配置
        config = parser.load_config()
        print("✓ 配置文件加载成功")
        
        # 测试验证配置
        errors = parser.validate_config(config)
        if errors:
            print(f"✗ 配置验证失败: {errors}")
            return False
        else:
            print("✓ 配置验证通过")
        
        # 测试获取全局配置
        global_config = parser.get_global_config()
        if global_config:
            print("✓ 全局配置解析成功")
        else:
            print("✗ 全局配置解析失败")
            return False
        
        # 测试获取 Hook 配置
        hook_config = parser.get_hook_config('pre-commit')
        if hook_config:
            print("✓ Hook 配置解析成功")
        else:
            print("✗ Hook 配置解析失败")
            return False
        
        return True
    except Exception as e:
        print(f"✗ 配置解析器测试失败: {e}")
        return False

def test_task_executor():
    """测试任务执行器"""
    print("\n测试任务执行器...")
    
    try:
        from core.task_executor import TaskExecutor
        from core.config_parser import TaskConfig, TaskType
        
        # 创建任务执行器
        executor = TaskExecutor()
        
        # 创建测试任务
        test_task = TaskConfig(
            name="测试任务",
            type=TaskType.COMMIT_MSG_VALIDATOR,
            config={
                'pattern': '^test:',
                'min_length': 5,
                'max_length': 50
            }
        )
        
        # 测试上下文
        context = {
            'commit_msg': 'test: 这是一个测试提交信息'
        }
        
        # 执行任务
        result = executor.execute_task(test_task, context)
        
        if result.status.value == 'success':
            print("✓ 任务执行成功")
        else:
            print(f"✗ 任务执行失败: {result.error}")
            return False
        
        return True
    except Exception as e:
        print(f"✗ 任务执行器测试失败: {e}")
        return False

def test_hook_manager():
    """测试 Hook 管理器"""
    print("\n测试 Hook 管理器...")
    
    try:
        from core.hook_manager import HookManager, HookType, HookContext
        
        # 创建 Hook 管理器
        manager = HookManager()
        
        # 测试创建上下文
        context = HookContext(hook_type=HookType.PRE_COMMIT)
        print("✓ Hook 上下文创建成功")
        
        # 注意：这里不执行实际的 Hook，因为可能需要 Git 环境
        print("✓ Hook 管理器初始化成功")
        
        return True
    except Exception as e:
        print(f"✗ Hook 管理器测试失败: {e}")
        return False

def test_plugins():
    """测试插件"""
    print("\n测试插件...")
    
    try:
        # 测试 ESLint 插件
        from plugins.lint.eslint import execute as eslint_execute
        print("✓ ESLint 插件导入成功")
        
        # 测试 npm audit 插件
        from plugins.security.npm_audit import execute as npm_audit_execute
        print("✓ npm audit 插件导入成功")
        
        # 测试 Jest 插件
        from plugins.test.jest import execute as jest_execute
        print("✓ Jest 插件导入成功")
        
        return True
    except Exception as e:
        print(f"✗ 插件测试失败: {e}")
        return False

def test_tools():
    """测试管理工具"""
    print("\n测试管理工具...")
    
    try:
        # 测试安装工具
        sys.path.insert(0, str(project_root / "tools"))
        from install import Installer
        print("✓ 安装工具导入成功")
        
        # 测试配置管理工具
        from config import ConfigManager
        print("✓ 配置管理工具导入成功")
        
        return True
    except Exception as e:
        print(f"✗ 管理工具测试失败: {e}")
        return False

def test_file_structure():
    """测试文件结构"""
    print("\n测试文件结构...")
    
    required_files = [
        "config/hooks.yaml",
        "core/config_parser.py",
        "core/task_executor.py", 
        "core/hook_manager.py",
        "tools/install.py",
        "tools/config.py",
        "plugins/lint/eslint.py",
        "plugins/security/npm_audit.py",
        "plugins/test/jest.py",
        "examples/basic-config.yaml",
        "examples/advanced-config.yaml",
        "docs/README.md",
        "requirements.txt",
        "setup.py"
    ]
    
    missing_files = []
    for file_path in required_files:
        if not (project_root / file_path).exists():
            missing_files.append(file_path)
    
    if missing_files:
        print(f"✗ 缺少文件: {missing_files}")
        return False
    else:
        print("✓ 所有必需文件都存在")
        return True

def main():
    """主测试函数"""
    print("Git Hooks 动态配置系统 - 系统测试")
    print("=" * 50)
    
    tests = [
        ("文件结构", test_file_structure),
        ("依赖检查", test_dependencies),
        ("模块导入", test_imports),
        ("配置解析器", test_config_parser),
        ("任务执行器", test_task_executor),
        ("Hook 管理器", test_hook_manager),
        ("插件系统", test_plugins),
        ("管理工具", test_tools),
    ]
    
    passed = 0
    failed = 0
    
    for test_name, test_func in tests:
        try:
            if test_func():
                passed += 1
            else:
                failed += 1
        except Exception as e:
            print(f"✗ {test_name} 测试异常: {e}")
            failed += 1
    
    print("\n" + "=" * 50)
    print(f"测试结果: {passed} 通过, {failed} 失败")
    
    if failed == 0:
        print("🎉 所有测试通过！系统可以正常使用。")
        return True
    else:
        print("❌ 存在测试失败，请检查相关问题。")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
